/*
 * @Author: Caijw
 * @Date: 2018-11-27 20:35:52
 * @LastEditors: Caijw
 * @LastEditTime: 2018-12-20 00:43:17
 * @Description: 周边列表
 */
import React, { Component } from 'react';
import {Link,NavLink} from 'react-router-dom';
import { Toast } from 'react-weui';
import {loadMore} from '../../../utils';
import '../../../static/css/common.less';
import { connect } from "react-redux";
import { CityPicker,Button } from 'react-weui';
import cnCity from '../../my/personal/address/cnCity';
import * as actions from '../../../store/action/ambitus';
import './list.less';

class AmbitusList extends Component {

    state = {
        cityName : '',
        kw : '',//关键字
        code : '',
        city_show : false,
        district_value : '',
        district_code : '',
        showPositionLoading : false,
    }
    
    componentWillMount() {
        var self =this;
        //判断是否定位了
        if(localStorage.getItem('positionType') == 'yes'){
            let positionAddress = localStorage.getItem('addressNow');
            self.changeCity(positionAddress);
        }else{
            this.setState({
                showPositionLoading : true,
            })
            
            var positionAddress = '';
            function getAddress() {
                //高德地图API
                //AMap.service解决只使用高德Geolocation功能提示Geolocation不是构造函数问题  
                AMap.service(["AMap.Geolocation"],function(){
                var geolocation = new AMap.Geolocation();
                geolocation.getCurrentPosition(function(status,result) {
                    if(status=="complete"){
                        positionAddress = result.addressComponent.province + ' ' +result.addressComponent.city + ' ' +result.addressComponent.district;
                        localStorage.setItem('addressNow', positionAddress);
                        localStorage.setItem('lat', result.position.lat);
                        localStorage.setItem('lng', result.position.lng);
                        self.props.ambitus.ambitus.lat = result.position.lat;
                        self.props.ambitus.ambitus.lng = result.position.lng;
                        // let address = localStorage.getItem('addressNow');
                        localStorage.setItem('positionType', 'yes');
                        self.setState({
                            showPositionLoading : false,
                        })
                        self.changeCity(positionAddress);

                        localStorage.setItem('addressCode', self.state.district_code)
                         //如果没有状态，请求数据
                        self.searchEvent();
                    }else{
                        getAddress();
                    }
                });
            });	
            }
            getAddress();
        }
       
    }

    //搜索
    componentDidMount = () =>{
        //如果没有状态，请求数据
        this.searchEvent();
        
        loadMore(this.mainContent,this.props.fetchAmbitusList);
    }
    //改变关键字
    changeKeyWord = (e) =>{
        this.setState({
            kw : e.target.value
        })
    }
    //搜索事件
    searchEvent = () =>{
        this.props.ambitus.ambitus.ambitusList = [];
        this.props.ambitus.ambitus.page = 1;
        this.props.ambitus.ambitus.kw = this.state.kw;
        
        this.props.ambitus.ambitus.code = this.state.district_code;
        let distanceCode = localStorage.getItem('addressCode');
        if(this.state.district_code == distanceCode){
            this.props.ambitus.ambitus.lat = localStorage.getItem('lat');
            this.props.ambitus.ambitus.lng = localStorage.getItem('lng');
        }else{
            this.props.ambitus.ambitus.lat = '';
            this.props.ambitus.ambitus.lng = '';
        }
        this.props.fetchAmbitusList();
    }
    //回车
    handleKeyDown = (e) =>{
        if(e.keyCode == 13){
            this.searchEvent();
        }
    }

    changeCity = (text) =>{
        let province = text.split(' ')[0];
        let city = text.split(' ')[1]
        let district = text.split(' ')[2];
        this.setState({district_value:  text.split(' ')[2], city_show: false});
        let cityArr = [];
        cnCity.forEach((item)=>{
            if(item.name == province){
                cityArr = item.sub;
                
            }
        })
        let districtArr = [];
        cityArr.forEach((item)=>{
            if(item.name == city){
                districtArr = item.sub;
                
            }
        })
        districtArr.forEach((item)=>{
            if(item.name == district){
                this.setState({district_code: item.code});
            }
        })
       
    }


    changeSelectCity = (text) =>{
        let self = this;
        let province = text.split(' ')[0];
        let city = text.split(' ')[1]
        let district = text.split(' ')[2];
        this.setState({district_value:  text.split(' ')[2], city_show: false});
        let cityArr = [];
        cnCity.forEach((item)=>{
            if(item.name == province){
                cityArr = item.sub;
            }
        })
        let districtArr = [];
        cityArr.forEach((item)=>{
            if(item.name == city){
                districtArr = item.sub;
                
            }
        })
        districtArr.forEach((item)=>{
            if(item.name == district){
                self.setState({district_code: item.code});
                if(item.code == this.state.district_code){

                }else{
                    setTimeout(()=>{
                        self.searchEvent();
                    })
                }
                
            }
        })
    }


    
    

    render() {
        return (
            <div>  
                 <CityPicker
                    data={cnCity}
                    onCancel={e=>this.setState({city_show: false})}
                    onChange={this.changeSelectCity}
                    show={this.state.city_show}
                />
                <Toast icon="loading" show={this.props.ambitus.fetching}>Loading...</Toast>
                <Toast icon="loading" show={this.state.showPositionLoading}>定位中</Toast>
                <div className="detail-region-my">
                  <div className="cate-search">
                    <div className="search-text"  onClick={ e=> { e.preventDefault(); this.setState({city_show: true})}}>{this.state.district_value}</div>
                    {/* <div className="search-text">{this.props.ambitus.data.city.name}</div> */}
                    <div className="search-input">
                        <img onClick={this.searchEvent} className="logo-search" src={require('../../../static/images2/logo-search.png')} alt="" />
                        <input
                            type="text"
                            name="phoneNumber"
                            placeholder="输入您要寻找的商店名称"
                            value={this.state.kw}
                            onChange={this.changeKeyWord}
                            onKeyDown={this.handleKeyDown}
                        />
                    </div>
                    </div>
                    <section class="content content-box" ref={ref=>this.mainContent=ref}>
                        {this.props.ambitus.ambitus.ambitusList.length>0?this.props.ambitus.ambitus.ambitusList.map((item, index)=>{
                                        return <NavLink to={"/aboutDetail/"+item.id}>
                                        <div className="product-item">
                                            <div className="pic"><img src={item.cover}></img></div>
                                            <div className="title">{item.name}</div>
                                            <div className="address">{item.address}</div>
                                            <div className="type"> {/*家具*/} </div>
                                            <div className="len">{item.distance || '暂无距离'} </div>
                                            <div className="plus">{item.promotion_text}</div>
                                            <div className="point"><img src={require('../../../static/images/point.png')}></img></div>
                                        </div>
                                    </NavLink> 
                                })
                            :<div></div>
                       }
                    </section>
                </div>
            </div>
        )
    }
}

//把组件和store关联在一起
export default connect((state)=>{return {...state}}, actions)(AmbitusList);
